import { getProfile, login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  props: {},
  state: {
    Token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 保存UserInfo
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 设置token
    setToken(state, newToken) {
      state.Token = newToken
      setToken(newToken)
    }
  },
  actions: {
    async userLogin(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res.data)
    },
    async getUserProfile(context) {
      const res = await getProfile()
      const userInfo = await getUserInfo(res.data.userId)
      const obj = { ...res.data, ...userInfo.data }
      context.commit('setUserInfo', obj)

      return res
    },
    // 用户退出
    logout(context) {
      context.commit('setToken', '')
      context.commit('setUserInfo', {})
      // 重置路由
      resetRouter()
    }
  }
}
